from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.edge.service import Service as EdgeService
try:
    from webdriver_manager.chrome import ChromeDriverManager
    from webdriver_manager.microsoft import EdgeChromiumDriverManager
    HAS_WEBDRIVER_MANAGER = True
except ImportError:
    HAS_WEBDRIVER_MANAGER = False
import time
import json
import os


class BrowserMCP:
    """浏览器操作 MCP (Model Context Protocol)"""
    
    def __init__(self, browser_type="chrome"):
        self.driver = None
        self.browser_type = browser_type
        self.config_file = os.path.join(os.path.dirname(__file__), 'browser_config.json')
        self.config = self._load_config()
    
    def start_browser(self, headless=False):
        """启动浏览器"""
        try:
            if self.browser_type == "chrome":
                options = webdriver.ChromeOptions()
                if headless:
                    options.add_argument('--headless')
                if HAS_WEBDRIVER_MANAGER:
                    service = ChromeService(ChromeDriverManager().install())
                    self.driver = webdriver.Chrome(service=service, options=options)
                else:
                    self.driver = webdriver.Chrome(options=options)
            elif self.browser_type == "edge":
                options = webdriver.EdgeOptions()
                if headless:
                    options.add_argument('--headless')
                if HAS_WEBDRIVER_MANAGER:
                    service = EdgeService(EdgeChromiumDriverManager().install())
                    self.driver = webdriver.Edge(service=service, options=options)
                else:
                    self.driver = webdriver.Edge(options=options)
            return True
        except Exception as e:
            print(f"启动浏览器失败: {e}")
            return False
    
    def navigate(self, url):
        """导航到URL"""
        try:
            self.driver.get(url)
            return True
        except Exception as e:
            print(f"导航失败: {e}")
            return False
    
    def find_element(self, by, value, timeout=10):
        """查找元素"""
        try:
            element = WebDriverWait(self.driver, timeout).until(
                EC.presence_of_element_located((by, value))
            )
            return element
        except TimeoutException:
            print(f"查找元素超时: {value}")
            return None
    
    def click_element(self, by, value, timeout=10):
        """点击元素"""
        try:
            print(f"[调试] 查找可点击元素: {by}={value}")
            element = WebDriverWait(self.driver, timeout).until(
                EC.element_to_be_clickable((by, value))
            )
            print(f"[调试] 元素找到，开始点击")
            element.click()
            print(f"[调试] 点击完成")
            return True
        except TimeoutException as e:
            print(f"点击元素失败: 查找元素超时 - {by}={value}")
            return False
        except Exception as e:
            print(f"点击元素失败: {type(e).__name__} - {str(e)}")
            import traceback
            traceback.print_exc()
            return False
    
    def input_text(self, by, value, text, timeout=10):
        """输入文本"""
        try:
            print(f"[调试] 查找元素: {by}={value}")
            element = WebDriverWait(self.driver, timeout).until(
                EC.element_to_be_clickable((by, value))
            )
            print(f"[调试] 元素找到，开始输入")
            element.clear()
            element.send_keys(text)
            print(f"[调试] 输入完成")
            return True
        except TimeoutException as e:
            print(f"输入文本失败: 查找元素超时 - {by}={value}")
            return False
        except Exception as e:
            print(f"输入文本失败: {type(e).__name__} - {str(e)}")
            import traceback
            traceback.print_exc()
            return False
    
    def get_text(self, by, value, timeout=10):
        """获取元素文本"""
        try:
            element = self.find_element(by, value, timeout)
            return element.text if element else None
        except Exception as e:
            print(f"获取文本失败: {e}")
            return None
    
    def execute_script(self, script):
        """执行JavaScript"""
        try:
            return self.driver.execute_script(script)
        except Exception as e:
            print(f"执行脚本失败: {e}")
            return None
    
    def scroll_to_element(self, by, value, timeout=10):
        """滚动到元素"""
        try:
            element = self.find_element(by, value, timeout)
            if element:
                self.driver.execute_script("arguments[0].scrollIntoView();", element)
                return True
            return False
        except Exception as e:
            print(f"滚动失败: {e}")
            return False
    
    def get_current_url(self):
        """获取当前URL"""
        try:
            return self.driver.current_url
        except Exception as e:
            print(f"获取URL失败: {e}")
            return None
    
    def get_page_title(self):
        """获取页面标题"""
        try:
            return self.driver.title
        except Exception as e:
            print(f"获取标题失败: {e}")
            return None
    
    def take_screenshot(self, save_path):
        """截屏"""
        try:
            self.driver.save_screenshot(save_path)
            return True
        except Exception as e:
            print(f"截屏失败: {e}")
            return False
    
    def close_browser(self):
        """关闭浏览器"""
        try:
            if self.driver:
                self.driver.quit()
            return True
        except Exception as e:
            print(f"关闭浏览器失败: {e}")
            return False
    
    def switch_to_window(self, window_index):
        """切换窗口"""
        try:
            self.driver.switch_to.window(self.driver.window_handles[window_index])
            return True
        except Exception as e:
            print(f"切换窗口失败: {e}")
            return False
    
    def get_cookies(self):
        """获取cookies"""
        try:
            return self.driver.get_cookies()
        except Exception as e:
            print(f"获取cookies失败: {e}")
            return None
    
    def add_cookie(self, cookie_dict):
        """添加cookie"""
        try:
            self.driver.add_cookie(cookie_dict)
            return True
        except Exception as e:
            print(f"添加cookie失败: {e}")
            return False
    
    def _load_config(self):
        """加载配置"""
        if os.path.exists(self.config_file):
            with open(self.config_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    
    def _save_config(self):
        """保存配置"""
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(self.config, f, ensure_ascii=False, indent=2)
    
    def save_login_info(self, site_name, username, password, login_url=None):
        """保存登录信息"""
        self.config[site_name] = {
            'username': username,
            'password': password,
            'login_url': login_url
        }
        self._save_config()
    
    def auto_login(self, site_name, username_selector, password_selector, submit_selector):
        """自动登录"""
        if site_name not in self.config:
            print(f"未找到 {site_name} 的登录信息")
            return False
        
        info = self.config[site_name]
        if info.get('login_url'):
            self.navigate(info['login_url'])
            time.sleep(2)
        
        self.input_text(By.CSS_SELECTOR, username_selector, info['username'])
        self.input_text(By.CSS_SELECTOR, password_selector, info['password'])
        self.click_element(By.CSS_SELECTOR, submit_selector)
        return True
    
    def search_and_get_results(self, search_url, search_input_selector, search_text, result_selector, max_results=10):
        """搜索并获取结果"""
        try:
            self.navigate(search_url)
            time.sleep(2)
            
            self.input_text(By.CSS_SELECTOR, search_input_selector, search_text)
            
            element = self.find_element(By.CSS_SELECTOR, search_input_selector)
            if element:
                element.send_keys(Keys.RETURN)
                time.sleep(3)
            
            results = self.driver.find_elements(By.CSS_SELECTOR, result_selector)[:max_results]
            return [r.text for r in results if r.text]
        except Exception as e:
            print(f"搜索失败: {e}")
            return []
    
    def type_at_cursor(self, text):
        """在当前光标位置输入文本（支持中文）"""
        try:
            import pyautogui
            import pyperclip
            # 使用剪贴板粘贴支持中文
            pyperclip.copy(text)
            pyautogui.hotkey('ctrl', 'v')
            time.sleep(0.5)
            return True
        except Exception as e:
            print(f"光标输入失败: {e}")
            return False
    
    def click_page_position(self, x, y):
        """点击页面指定位置"""
        try:
            import pyautogui
            pyautogui.click(x, y)
            return True
        except Exception as e:
            print(f"点击位置失败: {e}")
            return False
